<?php
/**
 * Created by PhpStorm.
 * User: Bostin
 * Date: 2019-02-14
 * Time: 17:40
 */

namespace Bostin\Translator;

use Bostin\Translator\Provider\AbstractProvider;
use Exception;

/**
 * Class Translator
 * @package Bostin\Translator
 */
class Translator
{
    const PROVIDER_BAIDU = 'baidu';
    const PROVIDER_TENCENT = 'tencent';
    const PROVIDER_YOUDAO = 'youdao';
    const PROVIDER_YEEKIT = 'yeekit';
    const PROVIDER_GOOGLE = 'google';
    const PROVIDER_MICROSOFT = 'microsoft';

    /**
     * @var string
     */
    private $providerCode;

    /**
     * @var array
     */
    private $config;

    /**
     * @var
     */
    private $provider;

    /**
     * Translator constructor.
     * @param string $providerCode
     * @param array $config
     */
    public function __construct(string $providerCode, array $config = [])
    {
        $this->providerCode = $providerCode;
        $this->config = $config;
    }

    /**
     * @return AbstractProvider
     * @throws Exception
     */
    public function getProvider(): AbstractProvider
    {
        if (is_null($this->provider)) {
            $code = implode('', array_map('ucfirst', explode('-', $this->providerCode)));
            $className = __NAMESPACE__ . '\\Provider\\' . $code . 'Provider';
            if (!class_exists($className)) {
                throw new Exception('Unknown provider');
            }
            $this->provider = new $className($this->config);
        }
        return $this->provider;
    }

    /**
     * @param string $sourceText
     * @param string $source
     * @param string $target
     * @return string|null
     * @throws Exception
     */
    public function text(string $sourceText, string $source, string $target): ?string
    {
        return $this->getProvider()->textTranslate($sourceText, $source, $target);
    }

    /**
     * @param string $sourceText
     * @param string $source
     * @param string $target
     * @return string|null
     * @throws Exception
     */
    public function image(string $sourceText, string $source, string $target): ?string
    {
        return $this->getProvider()->imageTranslate($sourceText, $source, $target);
    }

    /**
     * @param string $audioFormat
     * @param int $seq
     * @param int $isEnd
     * @param string $sourceText
     * @param string $source
     * @param string $target
     * @return string|null
     * @throws Exception
     */
    public function speech(string $audioFormat, int $seq, int $isEnd, string $sourceText, string $source, string $target): ?string
    {
        return $this->getProvider()->speechTranslate($audioFormat, $seq, $isEnd, $sourceText, $source, $target);
    }
}